<template>
  <view class="container">
    <!-- 上传区域 -->
    <view class="upload-area" @click="handleChooseMedia" v-if="fileList.length>=3 ? false :true">
      <view class="upload-icon">
        <image src="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/5c4d9907-0216-4dcb-847a-beae9087044b.png" mode="aspectFit"></image>
      </view>
      <text class="upload-text">上传图片/视频</text>
      <text class="upload-tip">(最多3个文件)</text>
    </view>

    <!-- 预览区域 -->
    <view class="preview-list">
      <view class="preview-item" v-for="(item, index) in fileList" :key="index">
        <!-- 图片预览 -->
        <image 
          v-if="item.fileType === 'image'" 
          :src="item.tempFilePath" 
          mode="aspectFill"
          @click="previewMedia(item.tempFilePath,index)"
        ></image>
        <!-- 视频预览 -->
        <view v-else-if="item.fileType === 'video'" class="video-wrapper">
			
          <video 
			style="width: 220rpx;height: 220rpx;"
			object-fit="contain"
			:id="'video'+index" 
            :src="item.tempFilePath" 
            controls
			autoplay
            :poster="item.thumbTempFilePath"
			show-fullscreen-btn
            show-center-play-btn
			@fullscreenchange="onFullscreenChange($event,index)"
          ></video>
          <view class="play-icon"></view>
        </view>
        
        <!-- 删除按钮 -->
        <view class="delete-btn" @click.stop="deleteMedia(index)">
          <text>×</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {$ossFilesForm} from '@/http/apiManager.js'
import storageManage from '@/util/storageManage.js'

const fileList = ref([])
const isShow = ref(false)
const paramsUrl = ref('')
let videoContext = null

const emit = defineEmits(['updateValue'])

// 选择媒体文件（支持多选）
const handleChooseMedia = async () => {
  if (fileList.value.length >= 3) {
    uni.showToast({ title: '最多上传3个文件', icon: 'none' })
    return
  }
  try {
    const res = await uni.chooseMedia({
      count: 1 - fileList.value.length, // 动态计算还能选多少个
      mediaType: ['image', 'video'],
      sourceType: ['album'],
      maxDuration: 40,
      // sizeType: ['compressed']
    })

    if (res.tempFiles && res.tempFiles.length > 0) {
      // 逐个处理选中的文件
      for (const file of res.tempFiles) {
        await processFile(file)
      }
    }
  } catch (err) {
    handleError(err)
  }
}

// 处理单个文件上传
const processFile = (file) => {
	console.log(file,'file')
  return new Promise((resolve) => {
    uni.getFileSystemManager().getFileInfo({
      filePath: file.tempFilePath,
      success({ size }) {
        $ossFilesForm({
          bizType: 'user',
          sourceFileName: getFileName(file.tempFilePath),
          sourceFileSize: size
        }).then(({ bizData }) => {
			console.log(bizData,'bizData111')
          const newFile = {
            ...file,
            url: bizData.ossFileUrl,
            uploadUrl: bizData.formActionUrl,
            formParams: bizData.formParams
          }
          fileList.value.push(newFile)
		  console.log(fileList.value,'fileList.value')
		  emit('updateValue',fileList.value)
          uploadFile(newFile)
          resolve()
        })
      }
    })
  })
}

// 上传文件到OSS
const uploadFile = (file) => {
  uni.showLoading({ title: '上传中...' })
  uni.uploadFile({
    url: file.uploadUrl,
    filePath: file.tempFilePath,
    name: 'file',
    header: { 'Content-Type': 'multipart/form-data' },
    formData: file.formParams,
    complete(res) {
		
      uni.hideLoading()
      if (res.statusCode !== 200 && res.statusCode !== 204) {
        uni.showToast({ title: '上传失败', icon: 'none' })
      }
    }
  })
}

// 全屏变化事件
const onFullscreenChange = (e, index) => {
  console.log('全屏事件:', e.detail, '索引:', index)
   // 防抖处理
    if (fullscreenTimer) clearTimeout(fullscreenTimer)
    
    let fullscreenTimer = setTimeout(() => {
      console.log('处理全屏事件:', e.detail)
      // 实际处理逻辑...
	  if (!videoContext) {
	    videoContext = uni.createVideoContext('video'+index, this)
	  }
	  
	  // 处理全屏状态变化
	  if (e.detail.fullScreen) {
	    console.log('进入全屏')
	  } else {
	    console.log('退出全屏')
	    videoContext.pause()
	  }
    }, 100)
}

// 预览媒体（图片/视频）
const previewMedia = (a,index) => {
	console.log(a,index,888999)
  const item = fileList.value[index]
  if (item.fileType === 'image') {
    uni.previewImage({
      current: index,
      urls: fileList.value
        .filter(f => f.fileType === 'image')
        .map(f => f.tempFilePath)
    })
  } 
}

// 删除媒体文件
const deleteMedia = (index) => {
  fileList.value.splice(index, 1)
  emit('updateValue',fileList.value)
}

// 错误处理
const handleError = (err) => {
  console.error('选择文件失败:', err)
  if (err.errMsg.includes('permission')) {
    uni.showModal({
      title: '权限申请',
      content: '需要相册权限才能选择文件',
      success: (res) => {
        if (res.confirm) uni.openSetting()
      }
    })
  }
}

// 获取文件名
const getFileName = (path) => {
  return path.substring(path.lastIndexOf('/') + 1)
}
</script>

<style scoped lang="less">
/* 保持原有样式不变 */
.container {
  // padding: 20rpx;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #ccc;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  background-color: #f9f9f9;
}
video{
	z-index: 20 !important;
}

.upload-icon image {
  width: 80rpx;
  height: 80rpx;
}

.upload-text {
  font-size: 22rpx;
  color: #666;
  margin-top: 10rpx;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
}

.preview-list {
  display: flex;
  // justify-content: space-between;
  flex-wrap: nowrap;
  gap: 30rpx;
}

.preview-item {
  position: relative;
  width: 30%;
  height: 220rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.preview-item image,
.preview-item .video-wrapper {
  width: 100%;
  height: 100%;
  // width: 500rpx;
  // height: 500rpx;
}

.video-wrapper {
  position: relative;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60rpx;
  height: 60rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
}

.play-icon::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-30%, -50%);
  border-width: 15rpx 0 15rpx 25rpx;
  border-style: solid;
  border-color: transparent transparent transparent #fff;
}

.delete-btn {
  position: absolute;
  z-index: 50;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 0 0 0 12rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-btn text {
  color: white;
  font-size: 36rpx;
  line-height: 1;
  margin-bottom: 4rpx;
}
</style>